import router from "./router";
import { getToken, removeToken } from "@/utils/auth"; // get token from cookie
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import store from "./store";

import getPageTitle from "@/utils/get-page-title";

NProgress.configure({ showSpinner: false }); // NProgress Configuration
const whiteList = ["/login"];

router.beforeEach(async (to, from, next) => {
	NProgress.start();
	document.title = getPageTitle(to.meta.title);
	const hasToken = getToken();
	if (hasToken) {
		if (to.path === "/login") {
			next({ path: "/" });
			NProgress.done();
		} else {
			const hasSetting = store.getters.setting;
			if (hasSetting) {
				next();
			} else {
				try {
					await store.dispatch("get_setting");
					next();
				} catch (error) {
					removeToken();
					next(`/login?redirect=${to.path}`);
					NProgress.done();
				}
			}
		}
	} else {
		if (whiteList.indexOf(to.path) !== -1) {
			next();
		} else {
			next(`/login?redirect=${to.path}`);
			NProgress.done();
		}
	}
});

router.afterEach(() => {
	NProgress.done();
});
